package com.sap.sap_mangers.controller;


import com.sap.sap_mangers.dto.user.RegisterUser;
import com.sap.sap_mangers.pojo.SapIp;
import com.sap.sap_mangers.pojo.User;
import com.sap.sap_mangers.service.CacheService;
import com.sap.sap_mangers.service.LoginService;
import com.sap.sap_mangers.service.UserService;
import com.sap.sap_mangers.until.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author 阿东
 * @date 2022/7/1 [14:09]
 */
@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private UserService userService;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private RedisCache redisCache;


    @PostMapping("/loginUser")
    public SimpleJson login(@RequestBody User user, HttpServletRequest request) {
        SimpleJson login = loginService.login(user);
        if (login.getCode() == 0) {
            //增加登录的时候ip日志
            String ipAddr = IpUtil.getIpAddr(request);
            SapIp sapIp = new SapIp(ipAddr, user.getUsername(), cacheService.getRealNameCache(cacheService.getRealNameCacheMap(), user.getUsername()), new Timestamp(System.currentTimeMillis()));
            userService.addIp(sapIp);
        }
        return login;
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/test")
    public SimpleJson test() {
        String username = JwtUtil.getUserForToken();
        return new SimpleJson(0, username);
    }

    @PreAuthorize("hasAuthority('游客')")
    @PostMapping("/quitLogin")
    public SimpleJson quitLogin() {
        return loginService.quitLogin();
    }


    @PostMapping("/registerUser")
    public SimpleJson registerUser(@RequestBody RegisterUser registerUser) {
        SimpleJson json;
        //事务处理
        try {
            json = userService.registerUser(registerUser);
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(2, "服务器异常，请稍后再试！");
        }
        return json;
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getWeatherAndRegisterIp")
    public SimpleJson getWeatherAndRegisterIp(HttpServletRequest request) {
        return new SimpleJson(loginService.getIpAndWeather(request));
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getIpByUsername")
    public SimpleJson getIpByUsername(@RequestParam("username") String username) {
        return new SimpleJson(userService.getIpByUsername(username));
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getIp")
    public SimpleJson getIp() {
        return new SimpleJson(userService.getIp());
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getIpOwner")
    public SimpleJson getIpOwner() {
        return new SimpleJson(userService.getIpByUsername(JwtUtil.getUserForToken()));
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getCity")
    public SimpleJson getCity(HttpServletRequest request) {
        return loginService.getCity(request);
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/confirmOnline")
    public SimpleJson confirmOnline() {
        Set<Object> cacheSet = redisCache.getCacheSet(ConstantUntil.CONFIRM_ONLINE_PEOPLE);
        cacheSet.add(JwtUtil.getUserForToken());
        redisCache.setCacheSet(ConstantUntil.CONFIRM_ONLINE_PEOPLE, cacheSet);
        return SimpleJson.SUCCESS;
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getOnlineData")
    public SimpleJson getOnlineData() {
        Map<String, Object> onlineData = redisCache.getCacheMap(ConstantUntil.ONLINE_PEOPLE_DATA);
        GregorianCalendar calendar = new GregorianCalendar();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour % 2 == 1) {
            hour -= 1;
        }
        Map<String, Integer> map = new LinkedHashMap<>();
        int size = onlineData.size();
        String time;
        while (size != 0) {
            if (hour < 10) {
                time = "0" + hour + ":00:00";
            } else {
                time = hour + ":00:00";
            }
            map.put(time, (Integer) onlineData.get(time));
            size--;
            hour-=2;
            if(hour<0){
                hour=22;
            }
        }
        List<String> list =new ArrayList<>(map.keySet());
        Map<String,Integer> result=new LinkedHashMap<>();
        for (int i = list.size() - 1; i >= 0; i--) {
            result.put(list.get(i),map.get(list.get(i)));
        }
        return new SimpleJson(0, result);
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getNowPeople")
    public SimpleJson getNowPeople() {
        Set<String> peopleNum = redisCache.getCacheSet(ConstantUntil.CONFIRM_ONLINE_PEOPLE);
        return new SimpleJson(peopleNum.size());
    }

    @PreAuthorize("hasAuthority('管理员')")
    @GetMapping("/getOnlinePeople")
    public SimpleJson getOnlinePeople() {
        return userService.getOnlinePeopleMessageCopy();
    }

}
